package com.mycontract.suitepro.contract

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.view.View
import android.webkit.WebSettings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mycontract.suitepro.R
import com.mycontract.suitepro.base.BaseActivity
import com.mycontract.suitepro.components.dialog.PermissionItem
import com.mycontract.suitepro.components.dialog.PermissionsDialog
import com.mycontract.suitepro.contract.adapter.ContractOrderAdapter
import com.mycontract.suitepro.databinding.ActivityContractSuiteContractSignWebBinding
import com.mycontract.suitepro.enums.PageTagEnum
import com.mycontract.suitepro.extend.*
import com.mycontract.suitepro.utils.AppConfigUtil
import com.mycontract.suitepro.utils.analytics.util.AnalyticsUtil
import java.net.URLEncoder

/** 合同确认页 */
@SuppressLint("CustomSplashScreen")
class ContractSignWebActivity : BaseActivity() {

    // 布局binding
    private lateinit var mActivityBinding: ActivityContractSuiteContractSignWebBinding
    private lateinit var mContractOrderAdapter: ContractOrderAdapter

    // 权限弹框
    private val mPermissionsDialog = PermissionsDialog()

    // 当前订单号
    private var curContractIndex = 0

    // 是否已滑动到最后
    private var mScrollToBottom = false

    // viewModel
    private val mContractViewModel by lazy {
        ViewModelProvider(this)[ContractViewModel::class.java]
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mContractViewModel)
        return list
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteTag(): String {
        return PageTagEnum.contract_order_sign.name.uppercase()
    }

    override fun onContractSuiteBindingContractSuiteContentContractSuiteView(): View {
        mActivityBinding = ActivityContractSuiteContractSignWebBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onContractSuiteContentContractSuiteViewContractSuiteBinded() {
        try {
            // 初始化
            initSubViews()
            initPermissionDialogUI()

            // 获取用户状态回调
            mContractViewModel.onGetContractOrderListLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mContractViewModel.mContractOrderList.clear()
                        mContractViewModel.mContractOrderList.addAll(result)
                        mContractOrderAdapter.notifyDataSetChanged()
                    }
                }
            }

            // 显示order id
            if (ContractSignManager.mOrderList.size > 1) {
                val item = ContractSignManager.mOrderList[curContractIndex]
                mActivityBinding.textContractOrderId.text = (item.orderId)
            }

            // 点击上一个合同
            mActivityBinding.imageContractOrderPrefix.setOnClickListener {
                if (curContractIndex > 0) {
                    curContractIndex = (curContractIndex - 1)
                    val item = ContractSignManager.mOrderList[curContractIndex]
                    mActivityBinding.textContractOrderId.text = (item.orderId)

                    mScrollToBottom = false

                    AppConfigUtil.mRevObjAppConfig?.let { config ->
                        config.signAds?.let { url ->
                            if (url.isNotBlank()) {
                                //拼接参数
                                val fullUrl =
                                    "${url}?orderId=${item.orderId}&fullName=${item.fullName}&product=${item.product}&currentAddress=${item.currentAddress}"
                                val encodeUrl = URLEncoder.encode(fullUrl, "UTF-8")

                                println("---》fullUrl： $fullUrl")
                                println("---》encodeUrl： $encodeUrl")

                                mActivityBinding.appWebview.loadUrl(fullUrl)

                                // 显示loading
                                showContractSuiteLodingContractSuiteDialog()

                                Handler(Looper.getMainLooper()).postDelayed({
                                    dismissContractSuiteLoadingContractSuiteDialog()
                                }, 3000)
                            }
                        }
                    }

                    // 打点
                    AnalyticsUtil.saveHitPointInfo(
                        type = ContractEvent.CONTRACT_CHECK_BEFORE,
                        remark = ""
                    )
                }
            }

            // 点击下一个合同
            mActivityBinding.imageContractOrderNext.setOnClickListener {
                if (curContractIndex < (ContractSignManager.mOrderList.size - 1)) {
                    curContractIndex = (curContractIndex + 1)
                    val item = ContractSignManager.mOrderList[curContractIndex]
                    mActivityBinding.textContractOrderId.text = (item.orderId)

                    mScrollToBottom = false

                    AppConfigUtil.mRevObjAppConfig?.let { config ->
                        config.signAds?.let { url ->
                            if (url.isNotBlank()) {
                                //拼接参数
                                val fullUrl =
                                    "${url}?orderId=${item.orderId}&fullName=${item.fullName}&product=${item.product}&currentAddress=${item.currentAddress}"
                                val encodeUrl = URLEncoder.encode(fullUrl, "UTF-8")

                                println("---》fullUrl： $fullUrl")
                                println("---》encodeUrl： $encodeUrl")

                                mActivityBinding.appWebview.loadUrl(fullUrl)

                                // 显示loading
                                showContractSuiteLodingContractSuiteDialog()

                                Handler(Looper.getMainLooper()).postDelayed({
                                    dismissContractSuiteLoadingContractSuiteDialog()
                                }, 3000)
                            }
                        }
                    }

                    // 打点
                    AnalyticsUtil.saveHitPointInfo(
                        type = ContractEvent.CONTRACT_CHECK_NEXT,
                        remark = ""
                    )
                }
            }

            // 点击签约
            mActivityBinding.textAdapterSubmit.setOnClickListener {
                // 打点
                AnalyticsUtil.saveHitPointInfo(
                    type = ContractEvent.CONTRACT_CHECK_SIGN,
                    remark = ""
                )

                val orderIds = mutableListOf<String>()
                val products = mutableListOf<String>()
                val tokens = mutableListOf<String>()

                ContractSignManager.mOrderList.forEach { item ->
                    orderIds.add(item.orderId)
                    products.add(item.product)
                    tokens.add(item.token)
                }

                ContractSignManager.mOrderId = orderIds.joinToString(",")
                ContractSignManager.mToken = tokens.joinToString(",")
                ContractSignManager.mProduct = products.joinToString(",")

                println("---> orderIds: ${ContractSignManager.mOrderId}")
                println("---> tokens: ${ContractSignManager.mToken}")
                println("---> products: ${ContractSignManager.mProduct}")

                // 查询权限
                val permissionList =
                    PermissionsDialog.getPermissionList(this@ContractSignWebActivity)
                println(permissionList)

                // 需要展示权限框
                if (permissionList.isNotEmpty()) {
                    // 设置权限数据
                    mPermissionsDialog.setPermissionList(permissionList)
                    // 展示
                    mPermissionsDialog.setShowDiaog(supportFragmentManager)

                } else {
                    // 去上报数据页
                    startContractSuiteToContractSuiteContractContractSuiteDataContractSuiteUploadContractSuitePage()
                }
            }

            // 加载第1个合同
            mScrollToBottom = false
            if (ContractSignManager.mOrderList.size > 0) {
                val firstItem = ContractSignManager.mOrderList.first()
                AppConfigUtil.mRevObjAppConfig?.let { config ->
                    config.signAds?.let { url ->
                        if (url.isNotBlank()) {
                            //拼接参数
                            val fullUrl =
                                "${url}?orderId=${firstItem.orderId}&fullName=${firstItem.fullName}&product=${firstItem.product}&currentAddress=${firstItem.currentAddress}"
                            println("---》fullUrl： $fullUrl")

//                            val encodeUrl = URLEncoder.encode(fullUrl, "UTF-8")
//                            println("---》encodeUrl： $encodeUrl")


                            mActivityBinding.appWebview.loadUrl(fullUrl)

                            // 显示loading
                            showContractSuiteLodingContractSuiteDialog()

                            Handler(Looper.getMainLooper()).postDelayed({
                                dismissContractSuiteLoadingContractSuiteDialog()
                            }, 3000)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        if (ContractSignManager.mOrderList.size > 1) {
            mActivityBinding.rlTopSwitchBar.visibility = View.VISIBLE
            mActivityBinding.textAdapterSubmit.text =
                getString(R.string.contract_suite_contract_start_sign_all_contract)
        } else {
            mActivityBinding.rlTopSwitchBar.visibility = View.GONE
            mActivityBinding.textAdapterSubmit.text =
                getString(R.string.contract_suite_contract_start_sign_contract)
        }
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuitePhoneStateContractSuitePass(realAgree: Boolean) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_PHONE_STATE, realAgree)
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteSMSContractSuitePass(realAgree: Boolean) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_SMS, realAgree)
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteContactsContractSuitePass(realAgree: Boolean) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_CONTRACTS, realAgree)
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteCalllogContractSuitePass(realAgree: Boolean) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_CALL_LOG, realAgree)
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initSubViews() {
        with(mActivityBinding.appWebview) {
            // 清理缓存--可开可不开
            clearCache(true)
            clearHistory()
            clearFormData()
            // 设置
            settings.setSupportZoom(true)
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.allowContentAccess = true
            settings.allowFileAccess = true
            settings.useWideViewPort = true
            settings.loadWithOverviewMode = true
            settings.builtInZoomControls = true
            settings.displayZoomControls = false
            settings.cacheMode = WebSettings.LOAD_NO_CACHE
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

            // JS支持（创建注入交互方法对象）
//            val jsInterfaceMfr = AppJavaScriptInterface(this@AppWebViewActivity)
//            addJavascriptInterface(jsInterfaceMfr, "android")
        }

        // 滑动监听
        mActivityBinding.appWebview.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            val totalHeight =
                mActivityBinding.appWebview.contentHeight * mActivityBinding.appWebview.scaleY
            val webViewHeight = mActivityBinding.appWebview.height

//            println("totalHeight:${totalHeight} webViewHeight:${webViewHeight} scrollY:${scrollY}")

            if ((scrollY >= webViewHeight) and (!mScrollToBottom)) {
                // 设置标志位
                mScrollToBottom = true

                // 打点
                AnalyticsUtil.saveHitPointInfo(
                    type = ContractEvent.CONTRACT_WEB_BOTTOM,
                    remark = ""
                )
            }
        }
    }

    /** 设置权限弹框模块 */
    private fun initPermissionDialogUI() {
        //设置请求权限回调
        mPermissionsDialog.setStartRequestPermissionClickListener { permission ->
            when (permission) {
                PermissionItem.TYPE_SMS -> {
                    requestContractSuiteSmsContractSuitePermission(permission)
                }
                PermissionItem.TYPE_CONTRACTS -> {
                    requestContractSuiteContactsContractSuitePermission(permission)
                }
                PermissionItem.TYPE_CALL_LOG -> {
                    requestContractSuiteCalllogContractSuitePermission(permission)
                }
                else -> {
                    requestContractSuitePhoneStateContractSuitePermission(permission)
                }
            }
        }

        //设置同意所有权限回调
        mPermissionsDialog.setAllRequestPermissionAgreeListener {
            // 去上报数据页
            startContractSuiteToContractSuiteContractContractSuiteDataContractSuiteUploadContractSuitePage()
        }
    }
}